// 用户管理界面
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:im_app/im/page/view/LoadingView.dart';
import 'package:im_app/im/page/view/component/cell/UserGroupItemView.dart';
import 'package:provider/provider.dart';
import 'package:super_sliver_list/super_sliver_list.dart';

import 'bloc/UserAndGroupListCubit.dart';

/// 用户和群组同时按照首字母展示
class UserAndGroupPage extends StatefulWidget {

  const UserAndGroupPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _ListState();
  }
}

class _ListState extends State<UserAndGroupPage> {
  late ListController _listController;
  late ScrollController _scrollController;

  @override
  void initState() {
    super.initState();
    _listController = ListController();
    _scrollController = ScrollController();
  }

  @override
  Widget build(BuildContext context) {
    final state = context.watch<UserAndGroupListCubit>().state;
    return LoadingView(state: state.state, child: _buildListView(context));
  }

  Widget _buildListView(BuildContext context) {
    final state = context.watch<UserAndGroupListCubit>().state;
    return Stack(
      children: [
        // Expanded(child: _buildPullView2()),
        // _buildPullView(context),
        _buildUserAndGroupList(context),
        Positioned(
          right: 10,
          child: Center(
            child: Column(
                children: state.letters
                    .asMap()
                    .map<int, Widget>((index, letter) => MapEntry(
                        index,
                        GestureDetector(
                          child: _buildLetter(letter),
                          onTap: () => _jumpToUser(state.letters, state.letterSizeMap, letter),
                        )))
                    .values
                    .toList()),
          ),
        )
      ],
    );
  }

  Widget _buildPullView(BuildContext context) {
    return EasyRefresh(
        // controller: _easyRefreshController,
        header: const ClassicHeader(
            processedText: "加载数据成功！",
            dragText: "下拉会加载数据",
            armedText: "放松加载数据",
            processingText: "正在加载数据！",
            readyText: "加载数据完数据"),
        footer: const ClassicFooter(),
        onRefresh: () async {
          await context.read<UserAndGroupListCubit>().loadData();
        },
        onLoad: () async {
          try {
            return await context.read<UserAndGroupListCubit>().loadMoreData();
          } catch (error, stackTrace) {
            print('error==');
          }
        },
        child: _buildUserAndGroupList(context));
  }

  /// 用户列表
  Widget _buildUserAndGroupList(BuildContext context) {
    final state = context.watch<UserAndGroupListCubit>().state;
    return SuperListView.builder(
      listController: _listController,
      controller: _scrollController,
      scrollDirection: Axis.vertical,
      itemCount: state.userGroups.length,
      physics: const BouncingScrollPhysics(),
      // shrinkWrap: true,
      cacheExtent: 5,
      itemBuilder: (context, index) {
        var preUserGroup = index > 0 ? state.userGroups.elementAt(index - 1) : null;
        return UserAndGroupItemView(userAndGroup: state.userGroups.elementAt(index), preUserGroup: preUserGroup);
      },
      // separatorBuilder: (context, index) {
      //   return Padding(padding: EdgeInsets.only(top: 5, bottom: 5), child: ListSeparator(),);
      // },
    );
  }

  Widget _buildLetter(String letter) {
    return Padding(
      padding: const EdgeInsets.only(left: 5, right: 10, top: 2, bottom: 2),
      child: Container(
        width: 20,
        decoration: const ShapeDecoration(
          shape: CircleBorder(),
          color: Colors.black12, // 圆点的颜色
        ),
        child: Center(
          child: Text(
            letter,
            style: const TextStyle(
              color: Colors.black87,
            ),
          ),
        ),
      ),
    );
  }

  /// 调整首字母处
  void _jumpToUser(List<String> letters, Map<String, int> letterSizeMap, String letter) async {
    var size = 0;
    print('Current letter0: ${letter}');
    for (var i = 0; i < letters.length; i++) {
      if (letters[i] == letter) {
        break;
      }
      size += letterSizeMap[letters[i]] ?? 0;
    }
    print('Current letter0: ${letter}, $size');
    _jumpToItem(size);
  }

  void _jumpToItem(int index) {
    _listController.jumpToItem(
      index: index,
      scrollController: _scrollController,
      alignment: 0.5,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _listController.dispose();
    _scrollController.dispose();
  }
}
